package com.aloda.orangebank.controller;

import com.aloda.orangebank.mapper.SysAdminMapper;
import com.aloda.orangebank.pojo.Admin;
import com.aloda.orangebank.pojo.PageBean;
import com.aloda.orangebank.pojo.Result;
import com.aloda.orangebank.pojo.User;
import com.aloda.orangebank.service.SysAdminService;
import com.aloda.orangebank.service.UserService;
import com.aloda.orangebank.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/system")
public class SysAdminController {

    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result adminLogin(@RequestBody Admin admin){
        log.info("当前登录的管理员：{}",admin);
        Admin a = sysAdminService.login(admin);
        if(a!=null){
            Map<String,Object> claims =new HashMap<>();
            claims.put("id",a.getId());
            claims.put("username",a.getUsername());
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前登录的管理员信息
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }

    /*
    *使用 Optional.ofNullable() 方法来处理可能为 null 的 begin 和 end 参数。这样可以在 begin 或 end 为 null 时,直接返回 null 作为 beginInBeijingTz
    * 和 endInBeijingTz。
    * 使用 map() 方法将 begin 和 end 分别加 8 小时,得到 beginInBeijingTz 和 endInBeijingTz。这种方式更简洁,也能够正确地处理可能为 null 的情况。
    * 这样做的好处是,即使前端传入的 begin 和 end 参数有可能为 null,代码也能够正确地处理,不需要额外的 if 语句。同时,代码也更加简洁和可读性更好。
     */
    @GetMapping("/normaltable")
    public Result normalTable(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              String username,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        // 将前端传递的 LocalDateTime 加 8 小时, 转换为北京时区
        LocalDateTime beginInBeijingTz = Optional.ofNullable(begin).map(b -> b.plusHours(8)).orElse(null);
        LocalDateTime endInBeijingTz = Optional.ofNullable(end).map(e -> e.plusHours(8)).orElse(null);

        log.info("分页查询，参数：{}, {}, {}, {}, {}", page, pageSize, username, beginInBeijingTz, endInBeijingTz);
        PageBean pageBean = sysAdminService.page(page, pageSize, username, beginInBeijingTz, endInBeijingTz);
        return Result.success(pageBean);
    }

    @GetMapping("/canceltable")
    public Result cancelTable(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              String username,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        // 将前端传递的 LocalDateTime 加 8 小时, 转换为北京时区
        LocalDateTime beginInBeijingTz = Optional.ofNullable(begin).map(b -> b.plusHours(8)).orElse(null);
        LocalDateTime endInBeijingTz = Optional.ofNullable(end).map(e -> e.plusHours(8)).orElse(null);

        log.info("分页查询，参数：{}, {}, {}, {}, {}", page, pageSize, username, beginInBeijingTz, endInBeijingTz);
        PageBean pageBean = sysAdminService.pageCancel(page, pageSize, username, beginInBeijingTz, endInBeijingTz);
        return Result.success(pageBean);
    }

    @GetMapping("/gettotals")
    public Result getTotals(){
        log.info("查询共有多少条用户数据");
        int totals = sysAdminService.getTotals();
        return Result.success(totals);
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        log.info("在后台系统中添加的用户：{}",user);
        if (userService.register(user)){
            return Result.success("添加成功");
        }
        return Result.error("该用户名已添加");
    }

    @PutMapping("/editUser")
    public Result editUser(@RequestBody User user){
        log.info("在后台系统更新的用户信息{}",user);
        int flag=userService.setUserInfo(user);
        if(flag==2){
            return Result.error("修改的用户名已注册！");
        }else if(flag==1){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @DeleteMapping("/canceluser")
    public Result cancelUser(String username){
        log.info("需要注销用户的用户名：{}",username);
        sysAdminService.cancelUser(username);
        return Result.success("注销成功");
    }

    @DeleteMapping("/reuser")
    public Result recoverUser(Integer id){
        log.info("需要恢复用户的用户id:{}",id);
        sysAdminService.recoverUser(id);
        return Result.success("恢复成功");
    }

    @DeleteMapping("/deleteuser")
    public Result deleteUser(String username){
        log.info("删除的用户：{}",username);
        sysAdminService.deleteUser(username);
        return Result.success("删除成功");
    }

    @PostMapping("/cancelusers")
    public Result cancelusers(@RequestBody List<User> users){
        log.info("注销的用户{}",users);
        return Result.error("error");
    }
}
